const mongoose = require('./mongoose.js');

var Schema = mongoose.Schema;
var accountBookSchema = new Schema({
	user_id: {type: Schema.Types.ObjectId, ref: 'User'},  //用户id
	account_book_type: String,	//账本类型
	type: String,	//收支
	type_name: String,	//支付类型
	money: Number,	//金额
	time: String,	//时间
	account: String	//账户
});
var AccountBook = mongoose.model('AccountBook', accountBookSchema);

module.exports = {
	insert: function(obj, callback){
		var acc = new AccountBook(obj);
		acc.save((err, data)=>{
			callback(err, data);
		});
	},
	update: function(id, data, callback){
		AccountBook.updateOne({_id: id}, {$set: data}, (err, data)=>{
			callback(err, data);
		});
	},
	remove: function(id, callback){
		AccountBook.deleteOne({_id: id}, (err, data)=>{
			callback(err, data);
		});
	},
	//记账页面
	getNowMonthData: function(u_id, month, callback){
		var pattern = new RegExp('^' + month);
		if(u_id == "") u_id = (mongoose.Types.ObjectId)("000000000000000000000000");
		else u_id = (mongoose.Types.ObjectId)(u_id);
		var nowmonthdata = {
			incometotal: 0,
			outcometotal: 0,
			data: [],
		}
		AccountBook.aggregate([{$match: {user_id: u_id, time: pattern}}, {$group: {_id: "$type", total: {$sum: "$money"}}}], (err, data)=>{
			if(!err && data != null){
				if(data[0]._id == "支出"){
					nowmonthdata.outcometotal = data[0].total;
					if(data[1] != null) nowmonthdata.incometotal = data[1].total;
				} else{
					if(data[1] != null) nowmonthdata.outcometotal = data[1].total;
					nowmonthdata.incometotal = data[0].total;
				}
				AccountBook.find({user_id: u_id, time: pattern}, (err, data)=>{
					nowmonthdata.data = data;
					callback(nowmonthdata);
				});
			}
			
		});
		
	},
	getPieReportForm: function(u_id, callback){
		if(u_id == "") u_id = (mongoose.Types.ObjectId)("000000000000000000000000");
		else u_id = (mongoose.Types.ObjectId)(u_id);
		AccountBook.aggregate([{$match: {user_id: u_id}}, {$group: {_id: {type: "$type", type_name: "$type_name"}, total: {$sum: "$money"}}}], (err, data)=>{
			callback(data);
		});
	},
	//资产-账户-点击
	getAccountTotal: function(u_id, callback){
		if(u_id == "") u_id = (mongoose.Types.ObjectId)("000000000000000000000000");
		else u_id = (mongoose.Types.ObjectId)(u_id);
		AccountBook.aggregate([{$match: {user_id: u_id}}, {$group: {_id: {acc: "$account", type: "$type"}, total: {$sum: "$money"}}}], (err, data)=>{
			callback(data);
		});
	},
	//账本累计收支，左边滑动窗口
	getAccountBookTotal: function(u_id, callback){
		if(u_id == "") u_id = (mongoose.Types.ObjectId)("000000000000000000000000");
		else u_id = (mongoose.Types.ObjectId)(u_id);
		console.log(u_id)
		AccountBook.aggregate([{$match: {user_id: u_id}}, {$group: {_id: {acc_book_type: "$account_book_type", type: "$type"}, total: {$sum: "$money"}}}], (err, data)=>{
			callback(data);
		});
	}
};